﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

public class VideoQTEGameController : Singleton<VideoQTEGameController> {

    public List<QTEContent> qTEContents;
    public VideoPlayer VideoPlayer;
    public RawImage image;
    public QTEGame QTEGame;
    public GameObject Success;
    public GameObject Fail;

    private QTEContent current;
    private int currentIndex;
    private bool isPlaying;
    private RenderTexture renderTexture;

    public void Start()
    {
        Fail.SetActive(false);
        Success.SetActive(false);
        renderTexture = new RenderTexture(1920, 1080, 16);
        VideoPlayer.targetTexture = renderTexture;
        image.texture = renderTexture;

        StartGame();
    }

    public void Update()
    {
        if (isPlaying && current != null)
        {
            if (VideoPlayer.frame >= current.ShowAt && VideoPlayer.frameCount != 0)
            {
                pauseAndShowQTEGame();
            }
        }

        if (isPlaying)
        {
            if ((ulong)VideoPlayer.frame >= VideoPlayer.frameCount && VideoPlayer.frameCount != 0)
            {
                Debug.Log("frame " + VideoPlayer.frame);
                Debug.Log("count " + VideoPlayer.frameCount);
                Debug.Log("video finish");
                isPlaying = false;
                showSuccessView();
            }
        }
    }

    public void StartGame()
    {
        if (qTEContents.Count > 0)
            current = qTEContents[currentIndex];
        isPlaying = true;
        VideoPlayer.Play();
    }

    public void Restart()
    {
        UnityEngine.SceneManagement.SceneManager.LoadScene("VideoGameScene");
    }

    private void nextQTEContent()
    {
        currentIndex++;
        if (qTEContents.Count > currentIndex)
            current = qTEContents[currentIndex];
        else
            current = null;
    }

    private void qteGameResult(bool result)
    {
        if (result)
        {
            continueAndEndQTEGame();
        }
        else
        {
            showFailView();
        }
    }

    private void pauseAndShowQTEGame()
    {
        isPlaying = false;
        VideoPlayer.Pause();
        VideoPlayer.frame = current.ShowAt;
        QTEGame.StartGame(current, qteGameResult);
    }

    private void continueAndEndQTEGame()
    {
        nextQTEContent();
        isPlaying = true;
        VideoPlayer.Play();
    }

    private void showFailView()
    {
        Fail.SetActive(true);
    }

    private void showSuccessView()
    {
        Success.SetActive(true);
    }
}

[Serializable]
public class QTEContent
{
    public float TimeLimit;
    public int ShowAt;
    public List<QTEKey> LeftQTEKeys;
    public List<QTEKey> RightQTEKeys;
}

[Serializable]
public class QTEKey
{
    public string Text;
    public KeyCode KeyCode;
}
